package com.imooc.distributelock.service;


import com.imooc.distributelock.lock.AbstractLock;
import com.imooc.distributelock.lock.RedisLock;
import com.imooc.distributelock.mapper.StockMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class StockService {

    @Resource
    private StockMapper stockMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public String deductStock(Long goodsId, Integer count) {
        //1.使用redis+lua脚本进行锁
        AbstractLock lock = new RedisLock(stringRedisTemplate, "lock:" + goodsId);
        try {
//            Boolean isLock = lock.tryLock(2500, TimeUnit.MILLISECONDS);
//            if (!isLock) {
//                return "系统繁忙，请稍后重试";
//            }
            lock.lock();
            //1.查询商品的库存数量
            Integer stockCount = stockMapper.selectEntityByGoodsId(goodsId);
            //2.判断库存数量是否充足
            if (stockCount < count) {
                return "库存不足";
            }
            //3.如果库存数量充足，则扣减库存
            else {
                Integer updateCount = stockMapper.updateStockByGoodsId(goodsId, stockCount - count);
                if (updateCount == 0) {
                    return "扣减库存失败";
                } else {
                    return "扣减库存成功";
                }
            }
        }catch (Exception e) {
            log.error("扣减库存异常，商品ID: {}, 数量: {}", goodsId, count, e);
            return "系统异常，请重试";
        } finally {
            try {
                lock.unlock();
            } catch (Exception e) {
                log.error("释放锁异常，商品ID: {}", goodsId, e);
            }
        }
    }
}
